<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<script type="text/javascript">
	const context_path = '<%=path%>';
</script>
<div id="car_list_grid-div">
    <form id="car_list_hiddenForm" action="<%=path%>/car/materialExcel" method="POST" style="display: none;">
        <input name="ids" id="car_list_ids" value=""/>
		<input name="queryFactoryCode" id="car_list_queryFactoryCode" value="">
        <input name="queryWarehouse" id="car_list_queryWarehouse" value="">
        <input name="queryCode" id="car_list_queryCode" value="">
		<input id="car_list_queryExportExcelIndex" name="queryExportExcelIndex" value=""/>
    </form>
    <form id="car_list_hiddenQueryForm" style="display:none;">
        <input name="code" value=""/>
        <input name="warehouse" value="">
        <input name="factoryCode" value="">
    </form>
    <c:if test="${operationCode.webSearch==1}">
    <div class="query_box" id="car_list_yy" title="查询选项">
         <form id="car_list_queryForm" style="max-width:100%;">
			 <ul class="form-elements">
			 	 <li class="field-group field-fluid3">
					<label class="inline" for="car_list_factoryCode" style="margin-right:20px;width: 100%;">
						 <span class="form_label" style="width:80px;">厂区：</span>
						 <input id="car_list_factoryCode" name="factoryCode" type="text" style="width: calc(100% - 85px);" placeholder="厂区">
					</label>
				 </li>
				 <li class="field-group field-fluid3">
					 <label class="inline" for="car_list_warehouse" style="margin-right:20px;width: 100%;">
						 <span class="form_label" style="width:80px;">仓库：</span>
						 <input id="car_list_warehouse" name="warehouse" type="text" style="width:  calc(100% - 85px);" placeholder="仓库">
					 </label>
				 </li>
				 <li class="field-group field-fluid3">
					 <label class="inline" for="car_list_code" style="margin-right:20px;width: 100%;">
						 <span class="form_label" style="width:80px;">行车编号：</span>
						 <input id="car_list_code" name="code" type="text" style="width: calc(100% - 85px);" placeholder="编号">
					 </label>
				 </li>

			 </ul>
			<div class="field-button" style="">
				<div class="btn btn-info" onclick="car_list_queryOk();">
					<i class="ace-icon fa fa-check bigger-110"></i>查询
				</div>
				<div class="btn" onclick="car_list_reset();"><i class="ace-icon icon-remove"></i>重置</div>
			</div>
		  </form>		 
    </div>
    </c:if>
    <div id="car_list_fixed_tool_div" class="fixed_tool_div">
        <div id="car_list_toolbar_" style="float:left;overflow:hidden;"></div>
    </div>
    <table id="car_list_grid-table" style="width:100%;height:100%;"></table>
    <div id="car_list_grid-pager"></div>
</div>
<script type="text/javascript" src="<%=path%>/plugins/public_components/js/iTsai-webtools.form.js"></script>
<script type="text/javascript">
	let car_list_oriData;
	let car_list_grid;
	let car_list_factory_selectid;
	let car_list_exportExcelIndex;

	$("input").keypress(function (e) {
		if (e.which == 13) {
			car_list_queryOk();
		}
	});

	$(function  (){
	    $(".toggle_tools").click();
	});
	
	$("#car_list_toolbar_").iToolBar({
	    id: "car_list_tb_01",
	    items: [
	        {label: "添加",hidden:"${operationCode.webAdd}"==="1", onclick:car_list_openAddPage, iconClass:'glyphicon glyphicon-plus'},
	        {label: "编辑",hidden:"${operationCode.webEdit}"==="1", onclick: car_list_openEditPage, iconClass:'glyphicon glyphicon-pencil'},
	        {label: "删除",hidden:"${operationCode.webDel}"==="1", onclick: car_list_deleteCars, iconClass:'glyphicon glyphicon-trash'},
	        {label: "出库中", hidden:"${operationCode.webOutstorage}"==="1",onclick:function(){car_list_outMiss();},iconClass:'icon-indent-left'},
	        {label: "入库中",hidden:"${operationCode.webInstorage}"==="1", onclick:function(){car_list_inMiss();},iconClass:'icon-indent-right'},
		    {label: "闲置",hidden:"${operationCode.webFree}"==="1", onclick:function(){car_list_isStart();},iconClass:'icon-check'},
	        {label: "导出",hidden:"${operationCode.webExport}"==="1", onclick:function(){car_list_toExcel();},iconClass:'icon-share'}
	   ]
	});

	const car_list_queryForm_data = iTsai.form.serialize($("#car_list_queryForm"));

	car_list_grid = jQuery("#car_list_grid-table").jqGrid({
			url : context_path + "/car/list.do",
		    datatype : "json",
		    colNames : [ "主键","行车编码", "行车名称","厂区编码","厂区名称","所属仓库","仓库区域","标签号","行车状态"],
		    colModel : [ 
                 {name : "id",index : "id",hidden:true},
                 {name : "code",index : "code",width : 30},
                 {name : "name",index : "name",width : 60},
                 {name : "factoryCode",index : "factoryCode",width : 40},
                 {name : "factoryName",index : "factoryName",width : 60},
                 {name : "warehouseName",index : "warehouseName",width :60},
                 {name : "warehouseArea",index : "warehouseArea",width :50},
				 {name : "tag",index : "tag",width :60},
                 {name : "state",index : "state",width : 30,formatter:function(cellvalue,option,rowObject){
	                	if(cellvalue===0) {
	                		return "入库中";
						}else if(cellvalue===1) {
	                    	return "出库中";
						}else if(cellvalue===2) {
	                    	return "闲置";
						}
	                }
                }
		    ],
		    rowNum : 20,
		    rowList : [ 10, 20, 30 ],
		    pager : "#car_list_grid-pager",
		    sortname : "id",
		    sortorder : "asc",
            altRows: true,
            viewrecords : true,
            hidegrid:false,
     	    autowidth:true, 
            multiselect:true,
            multiboxonly: true,
            loadComplete : function(data) {
            	var table = this;
            	setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
            	car_list_oriData = data;
            },
            emptyrecords: "没有相关记录",
            loadtext: "加载中...",
            pgtext : "页码 {0} / {1}页",
            recordtext: "显示 {0} - {1}共{2}条数据"
	});

	jQuery("#car_list_grid-table").navGrid("#car_list_grid-pager", {edit:false,add:false,del:false,search:false,refresh:false})
	.navButtonAdd("#car_list_grid-pager",{
		caption:"",
		buttonicon:"fa fa-refresh green",
		onClickButton: function(){
			$("#car_list_grid-table").jqGrid("setGridParam", {
			  postData: {queryJsonString:""} //发送数据
			}).trigger("reloadGrid");
		}
	}).navButtonAdd("#car_list_grid-pager",{
        caption: "",
        buttonicon:"fa icon-cogs",
        onClickButton : function (){
            jQuery("#car_list_grid-table").jqGrid("columnChooser",{
                done: function(perm, cols){
                    // dynamicColumns(cols,materials_list_dynamicDefalutValue);
                    $("#car_list_grid-table").jqGrid("setGridWidth", $("#car_list_grid-div").width());
					car_list_exportExcelIndex = perm;
                }
            });
        }
    });

	$(window).on("resize.jqGrid", function () {
		$("#car_list_grid-table").jqGrid("setGridWidth", $(window).width()-$("#sidebar").width() -7);
		$("#car_list_grid-table").jqGrid("setGridHeight",  $(".container-fluid").height()-10- $("#car_list_yy").outerHeight(true)-
		$("#car_list_fixed_tool_div").outerHeight(true)- $("#car_list_grid-pager").outerHeight(true)- $("#gview_car_list_grid-table .ui-jqgrid-hdiv").outerHeight(true));
	});
	$(window).triggerHandler("resize.jqGrid");
	
	/**打开添加页面*/
	function car_list_openAddPage(){
		$.post(context_path + "/car/toAdd.do", {}, function (str){
			$queryWindow=layer.open({
			    title : "行车添加",
		    	type:1,
		    	skin : "layui-layer-molv",
		    	area : "600px",
		    	shade : 0.6, //遮罩透明度
			    moveType : 1, //拖拽风格，0是默认，1是传统拖动
			    anim : 2,
			    content : str,
			    success: function (layero, index) {
	                layer.closeAll('loading');
	            }
			});
		});
	}

	/**打开编辑页面*/
	function car_list_openEditPage(){
		const selectAmount = getGridCheckedNum("#car_list_grid-table");
		if(selectAmount==0){
			layer.msg("请选择一条记录！",{icon:2});
			return;
		}else if(selectAmount>1){
			layer.msg("只能选择一条记录！",{icon:8});
			return;
		}
		layer.load(2);
		$.post(context_path+'/car/toAdd.do', {
			id:jQuery("#car_list_grid-table").jqGrid("getGridParam", "selrow")
		}, function(str){
			$queryWindow = layer.open({
				title : "行车编辑",
				type: 1,
			    skin : "layui-layer-molv",
			    area : "600px",
				shade: 0.6, //遮罩透明度
				moveType: 1, //拖拽风格，0是默认，1是传统拖动
				content: str,//注意，如果str是object，那么需要字符拼接。
				success:function(layero, index){
			   		layer.closeAll("loading");
			    }
			});
		}).error(function() {
			layer.closeAll();
	    	layer.msg("加载失败！",{icon:2});
		});
	}

	/**出库中*/
	function car_list_outMiss() {
		const selectAmount = getGridCheckedNum("#car_list_grid-table");
		if(selectAmount<1){
			layer.confirm("确定设置所有航车吗？", function() {
				$.post(context_path+'/car/outMiss.do?ids='+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"),{},function success(){
					layer.msg('更新成功',{icon:1,time:1200});
					jQuery("#car_list_grid-table").trigger("reloadGrid");
				});
			});
		}else{
			$.post(context_path+'/car/outMiss.do?ids='+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"),{},function success(){
				layer.msg('更新成功',{icon:1,time:1200});
				jQuery("#car_list_grid-table").trigger("reloadGrid");
			});
		}
    }

    /**入库中*/
	function car_list_inMiss() {
		const selectAmount = getGridCheckedNum("#car_list_grid-table");
		if(selectAmount<1){
			layer.confirm("确定设置所有航车吗？", function() {
				$.post(context_path+'/car/inMiss.do?ids='+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"),{},function success(){
					layer.msg('更新成功',{icon:1,time:1200});
					jQuery("#car_list_grid-table").trigger("reloadGrid");
				});
			});
		}else {
			$.post(context_path+'/car/inMiss.do?ids='+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"),{},function success(){
				layer.msg('更新成功',{icon:1,time:1200});
				jQuery("#car_list_grid-table").trigger("reloadGrid");
			});
		}
    }

    /**闲置*/
    function car_list_isStart() {
		const selectAmount = getGridCheckedNum("#car_list_grid-table");
		if(selectAmount<1){
			layer.confirm("确定设置所有航车吗？", function() {
				$.post(context_path+'/car/isStart.do?ids='+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"),{},function success(){
					layer.msg('更新成功',{icon:1,time:1200});
					jQuery("#car_list_grid-table").trigger("reloadGrid");
				});
			});
		}else {
			$.post(context_path+'/car/isStart.do?ids='+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"),{},function success(){
				layer.msg('更新成功',{icon:1,time:1200});
				jQuery("#car_list_grid-table").trigger("reloadGrid");
			});
		}

    }

	//删除
	function car_list_deleteCars(){
		const checkedNum = getGridCheckedNum("#car_list_grid-table", "id");  //选中的数量
	    if (checkedNum == 0) {
	    	layer.alert("请选择一个要删除的行车！");
	    } else {
	        layer.confirm("确定删除选中的行车？", function() {
	    		$.ajax({
	    			type : "POST",
	    			url : context_path + "/car/deleteCars.do?ids="+jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow") ,
	    			dataType : "json",
	    			cache : false,
	    			success : function(data) {
	    				layer.closeAll();
	    				if (Boolean(data.result)) {
	    					layer.msg(data.msg, {icon: 1,time:1000});
	    				}else{
	    					layer.msg(data.msg, {icon: 7,time:1000});
	    					
	    				}
	    				car_list_grid.trigger("reloadGrid");  //重新加载表格
	    			}
	    		});
	    	});
	    }  
	}
/**
 * 查询按钮点击事件
 */
 function car_list_queryOk(){
	 var queryParam = iTsai.form.serialize($("#car_list_queryForm"));
	 //执行父窗口中的js方法：将当前窗口中的form的值传递到父窗口，并放到父窗口中隐藏的form中，接着执行刷新父窗口列表的操作
	 car_list_queryByParam(queryParam);
}

 function car_list_queryByParam(jsonParam) {
    iTsai.form.deserialize($("#car_list_hiddenQueryForm"), jsonParam);
	 const queryParam = iTsai.form.serialize($("#car_list_hiddenQueryForm"));
	 const queryJsonString = JSON.stringify(queryParam);
	 $("#car_list_grid-table").jqGrid("setGridParam", {
		postData: {queryJsonString: queryJsonString}
	}).trigger("reloadGrid");
}
 
 //重置
function car_list_reset(){
	 car_list_factory_selectid='';
	 $("#car_list_queryForm #car_list_factoryCode").select2("val","");
     $("#car_list_queryForm #car_list_warehouse").select2("val","");
     $("#car_list_queryForm #car_list_type").select2("val","");
	 iTsai.form.deserialize($("#car_list_queryForm"),car_list_queryForm_data); 
	 car_list_queryByParam(car_list_queryForm_data);
}

//厂区
$("#car_list_queryForm #car_list_factoryCode").select2({
    placeholder: "选择厂区",
    minimumInputLength:0,   //至少输入n个字符，才去加载数据
    allowClear: true,  //是否允许用户清除文本信息
    delay: 250,
    formatNoMatches:"没有结果",
    formatSearching:"搜索中...",
    formatAjaxError:"加载出错啦！",
    ajax : {
        url: context_path+"/factoryArea/getFactoryList",
        type:"POST",
        dataType : 'json',
        delay : 250,
        data: function (term,pageNo) {     //在查询时向服务器端传输的数据
            term = $.trim(term);
            return {
                queryString: term,    //联动查询的字符
                pageSize: 15,    //一次性加载的数据条数
                pageNo:pageNo    //页码
            }
        },
        results: function (data,pageNo) {
			const res = data.result;
			if(res.length>0){   //如果没有查询到数据，将会返回空串
				const more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                return {
                    results:res,more:more
                };
            }else{
                return {
                    results:{}
                };
            }
        },
        cache : true
    }
});


$("#car_list_queryForm #car_list_factoryCode").on("change.select2",function(){
    $("#car_list_queryForm #car_list_factoryCode").trigger("keyup")
	car_list_factory_selectid = $("#car_list_queryForm #car_list_factoryCode").val();
});

function car_list_toExcel(){
    $("#car_list_hiddenForm #car_list_ids").val(jQuery("#car_list_grid-table").jqGrid("getGridParam", "selarrrow"));
    $("#car_list_hiddenForm #car_list_queryFactoryCode").val($("#car_list_queryForm #car_list_factoryCode").val());
    $("#car_list_hiddenForm #car_list_queryWarehouse").val($("#car_list_queryForm #car_list_warehouse").val());
    $("#car_list_hiddenForm #car_list_queryCode").val($("#car_list_queryForm #car_list_code").val());
	$("#car_list_hiddenForm #car_list_queryExportExcelIndex").val(car_list_exportExcelIndex);
    $("#car_list_hiddenForm").submit();
}

$("#car_list_queryForm #car_list_warehouse").select2({
        placeholder: "选择仓库",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/car/selectWarehouse",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    factoryCodeId:car_list_factory_selectid
                }
            },
            results: function (data, pageNo) {
				const res = data.result;
				if (res.length > 0) { //如果没有查询到数据，将会返回空串
					const more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
</script>